const app = getApp()
var time = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagetemp: [], //图片列表
    videolist: [], //视频列表
    isSwitch: false, //查看图片是否需要密码
    bodyheight: ['身高:保密', '150CM', '155CM', '158CM', '160CM', '162CM', '163CM', '164CM', '165CM', '168CM', '170CM', '172CM', '173CM', '175CM', '180CM', '182CM', '185CM', '187CM', '188CM', '190CM', '195CM'],
    bodyheightValue: [0, 150, 155, 158, 160, 162, 163, 164, 165, 168, 170, 172, 173, 175, 180, 182, 185, 187, 188, 190, 195],
    bodyheight_ind: 0,
    bodyweight: ['体重:保密', '45公斤', '48公斤', '50公斤', '52公斤', '54公斤', '56公斤', '58公斤', '60公斤', '65公斤', '68公斤', '70公斤', '72公斤', '75公斤', '77公斤', '80公斤', '82公斤', '85公斤', '88公斤', '90公斤', '92公斤', '95公斤', '100公斤'],
    bodyweightValue: [0, 45, 48, 50, 52, 54, 56, 58, 60, 65, 68, 70, 72, 75, 77, 80, 82, 85, 88, 90, 92, 95, 100],
    bodyweight_ind: 0,
    sex: ['女', '男'],
    sex_ind: 0,
    age: ['请选择年龄', '18岁', '19岁', '20岁', '21岁', '22岁', '23岁', '24岁', '25岁', '26岁', '27岁', '28岁', '29岁', '30岁', '31岁', '32岁', '33岁', '34岁', '35岁', '36岁', '37岁', '38岁', '39岁', '40岁', '41岁', '42岁', '43岁', '44岁', '45岁', '46岁', '47岁', '48岁', '49岁', '50岁', '51岁', '52岁', '53岁', '54岁', '55岁', '56岁', '57岁', '58岁', '59岁', '60岁', '61岁', '62岁', '63岁', '64岁', '65岁', '66岁', '67岁', '68岁', '69岁', '70岁'],
    ageValue: [0, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70],
    age_ind: 0,
    education: ['学历:保密', '无文化', '小学', '初中', '高中', '中专', '大专', '大学', '硕士', '博士'],
    education_ind: 0,
    family: ['家庭:保密', '独生子女', '兄弟2人', '兄妹2人', '兄弟3人', '兄妹3人', '兄弟4人', '兄妹4人'],
    family_ind: 0,
    marriage: ['未婚', '离异', '丧偶'],
    marriage_ind: 0,
    houses: ['购房:保密', '1套房', '2套房', '3套房', '4套房', '5套房', '大于5套房', ],
    housesValue: [0, 1, 2, 3, 4, 5, 6],
    houses_ind: 0,
    region: ['安徽省', '蚌埠市', '全部'],
    customItem: '全部',
    istip_name: false,
    isfoucs_name: false,
    istip_age: false, //用户没有填写的时候给出红色边框    
    istip_phones: false,
    isfoucs_phones: false,
    istip_claim: false,
    isfoucs_claim: false,
    switch2Checked:false,//是否允许转发到朋友圈
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var admin_openid = wx.getStorageSync('admin_openid')
    if (typeof (admin_openid) == "undefined" || admin_openid == 0) {
      wx.reLaunch({
        url: '/pages/admin/admin',
      })
    }

  },
  istip: function (e) {
    //关闭红色提示框,传递一个提示框的名称
    let tip = e.target.dataset.name
    this.setData({
      [tip]: false, //关闭红色提示框
    })

  },
  formSubmit: function (e) {
    /**提交表单 */
    var name = e.detail.value.name; //姓名
    var bodyheight = this.data.bodyheightValue[this.data.bodyheight_ind]; //身高
    var bodyheight_ind = this.data.bodyheight_ind; //身高值,用在编辑中的默认选中记录
    var bodyweight = this.data.bodyweightValue[this.data.bodyweight_ind]; //体重
    var bodyweight_ind = this.data.bodyweight_ind; //体重,用在编辑中的默认选中记录
    var sex = this.data.sex[this.data.sex_ind]; //性别
    var sex_ind = this.data.sex_ind; //性别
    var age = this.data.ageValue[this.data.age_ind]; //年龄
    var age_ind = this.data.age_ind; //年龄
    var education = this.data.education[this.data.education_ind]; //学历
    var education_ind = this.data.education_ind; //学历
    var family = this.data.family[this.data.family_ind]; //家庭成员
    var family_ind = this.data.family_ind; //家庭成员
    var marriage = this.data.marriage[this.data.marriage_ind]; //婚姻状态
    var marriage_ind = this.data.marriage_ind; //婚姻状态
    var houses = this.data.housesValue[this.data.houses_ind]; //购房状态
    var houses_ind = this.data.houses_ind; //购房状态
    var phones = e.detail.value.phones; //红娘电话
    var phone = e.detail.value.phone; //客户电话
    var claim = e.detail.value.claim; //择偶条件
    var directions = e.detail.value.directions; //红娘说
    var imageispwd = this.data.isSwitch; //图片是否需要密码
    var imagepwd = e.detail.value.imagepwd; //查看图片密码
    var address = this.data.region; //用户的地址
    var switch2Checked= this.data.switch2Checked //是否允许朋友圈

    if (typeof (name) == "undefined" || name == 0) {
      wx.showToast({
        title: '姓名不能为空',
        icon: 'none'
      })

      this.setData({
        istip_name: true,
        isfocus_name: true
      })
      return;
    }


    if (age == 0) {
      wx.showToast({
        title: '年龄必须填写哟',
        icon: 'none'
      })
      this.setData({
        istip_age: true,
      })
      return;
    }


    if (typeof (phone) == "undefined" || phone == 0) {
      phone = '18800000000'
    }

    // var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    // if (!myreg.test(phone)) {
    //   wx.showToast({
    //     title: '客户手机号码不正确',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }


    if (typeof (phones) == "undefined" || phones == 0) {
      wx.showToast({
        title: '红娘电话不能为空',
        icon: 'none'
      })
      this.setData({
        istip_phones: true,
        isfocus_phones: true
      })
      return;
    }

    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if (!myreg.test(phones)) {
      wx.showToast({
        title: '对外红娘手机号码不正确',
        icon: 'none',
        duration: 2000
      })
      this.setData({
        istip_phones: true,
        isfocus_phones: true
      })
      return;
    }

    if (typeof (claim) == "undefined" || claim == 0) {
      wx.showToast({
        title: '择偶标准不能为空',
        icon: 'none'
      })
      this.setData({
        istip_claim: true,
        isfocus_claim: true
      })
      return;
    }

    if (claim.length < 6) {
      wx.showToast({
        title: '择偶标准最少6个字',
        icon: 'none'
      })
      this.setData({
        istip_claim: true,
        isfocus_claim: true
      })
      return;
    }

    if (this.data.imagetemp.length == 0) {
      wx.showToast({
        title: '至少要上传一张图片',
        icon: 'none'
      })

      return;
    }



    /**准备上传图片和表单 */
    this.uploadimg({
      path: this.data.imagetemp, //这里是图片路径
      video: this.data.videolist, //视频的路径云文件的全地址
      name: name, //姓名
      bodyheight: bodyheight, //身高
      bodyheight_ind: bodyheight_ind,
      bodyweight: bodyweight, //体重
      bodyweight_ind: bodyweight_ind,
      sex: sex, //性别
      sex_ind: sex_ind,
      age: age, //年龄
      age_ind: age_ind,
      education: education, //学历
      education_ind: education_ind,
      family: family, //家庭成员
      family_ind: family_ind,
      marriage: marriage, //婚姻状态
      marriage_ind: marriage_ind,
      houses: houses, //购房状态
      houses_ind: houses_ind,
      phones: phones, //红娘电话
      phone: phone, //客户电话
      claim: claim, //择偶条件
      directions: directions, //红娘说
      imageispwd: imageispwd, //查看图片是否需要密码?
      imagepwd: imagepwd, //查看图片密码
      address: address, //用户的地址
      hico: [], //必须为空
      switch2Checked:switch2Checked //允许朋友圈
    });



  },
  uploadimg: function (data) {
    console.log('uploadimg:', data)
    /**增加表单数据到数据库 */
    var that = this,
      hico = data.hico.length > 0 ? data.hico : [], //当前上传的哪张图片
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    if (data.path.length == 0) {
      console.log('等于0')
      that.uploadData(data)
    } else {
      console.log('有图片不等于0')
      wx.showLoading({
        title: '正在上传第' + (i + 1) + '个图片',
      })

      wx.cloud.uploadFile({
        cloudPath: `user/${time.formatTime(new Date)}/${Math.floor(Math.random() * 100000000)}.jpg`, // 上传至云端的路径
        filePath: data.path[i], // 临时文件路径
        success: res => {
          if (res.statusCode == 2) {
            success++; //图片上传成功，图片上传成功的变量+1
          } else {
            fail++; //图片上传失败，图片上传失败的变量+1
          }
        },
        fail: err => {
          fail++; //图片上传失败，图片上传失败的变量+1
        },
        complete: img => {
          console.log('img:', i, img)
          i++; //这个图片执行完上传后，开始上传下一张
          console.log('i是否等于path长度:', i == data.path.length)
          if (i == data.path.length) { //当图片传完时，停止调用 ,
            if (img.statusCode >= 200) { //把上传成功的返回增加到 data.hico去
              hico.push(img.fileID)
              data.hico = hico
            }
            console.log('hico:', data.hico)
            that.uploadData(data)



          } else { //若图片还没有传完，则继续调用函数
            if (img.statusCode >= 200) { //把上传成功的返回增加到 data.hico去
              hico.push(img.fileID)
              data.hico = hico
            }
            data.i = i;
            data.success = success;
            data.fail = fail;
            that.uploadimg(data);
          }

        }
      })


    }



  },
  uploadData: function (data) {
    console.log('uploadData:', data)
    /**把信息增加到数据库 */
    wx.cloud.init()
    const db = wx.cloud.database();
    const next = db.collection('user');
    wx.showLoading({
      title: '正在增加...',
    })
    wx.cloud.callFunction({
      name: 'id',
    }).then(id => {
      console.log('唯一id:', id.result)
      next.add({
          data: {
            name: data.name, //姓名
            bodyheight: data.bodyheight, //身高
            bodyheight_ind: parseInt(data.bodyheight_ind),
            bodyweight: data.bodyweight, //体重
            bodyweight_ind: parseInt(data.bodyweight_ind),
            sex: data.sex, //性别
            sex_ind: parseInt(data.sex_ind),
            age: data.age, //年龄
            age_ind: parseInt(data.age_ind),
            education: data.education, //学历
            education_ind: parseInt(data.education_ind),
            family: data.family, //家庭成员
            family_ind: parseInt(data.family_ind),
            marriage: data.marriage, //婚姻状态
            marriage_ind: parseInt(data.marriage_ind),
            houses: data.houses, //购房状态
            houses_ind: parseInt(data.houses_ind),
            phones: data.phones, //红娘电话
            phone: data.phone, //客户电话
            claim: data.claim, //择偶条件
            directions: data.directions, //红娘说
            access: 0, //访问量
            zan: 0, //点赞量
            image: data.hico, //图片列表
            video: data.video, //视频列表
            imageispwd: data.imageispwd, //查看图片是否需要密码?
            imagepwd: data.imagepwd, //查看图片的密码
            //status: app.globalData.isvip ? true : false, //显示 true为显示 false为不显示 如果是vip则不用审核
            status:true,//暂时关闭审核,先通过然后在喝茶真实性
            id: id.result, //用户的编号,用在二维码参数里面      
            address: data.address, //用户的地址
            time: db.serverDate(), //增加的时间
            pengyouquan:data.switch2Checked//是否允许朋友圈
          }
        })
        .then(res => {
          //数据增加成功,跳转到下一页
          console.log(res)
          wx.hideLoading()
          wx.reLaunch({
            url: '../a_addok/a_addok?name=' + data.name + '&age=' + data.age + '&sex=' + data.sex + '&marriage=' + data.marriage + '&sid=' + res._id + '&id=' + id.result,
          })

        })
      console.log('app.isvip:', app.globalData.isvip)
      //如果不是vip红娘,则通知管理员审核
      //if (!app.globalData.isvip) {
        wx.cloud.callFunction({
          name: 'sendMessage',
          data: {
            text: '红娘提交了新的信息:' + data.name + ' ' + data.sex + ' ' + data.marriage + ' 请审核'
          }
        }).then(res => {
          console.log(res)
        })
      //}



    })



  },
  bodyheight: function (e) {
    /**选择了身高 */
    console.log(e.detail.value)
    this.setData({
      bodyheight_ind: e.detail.value
    })
  },
  bodyweight: function (e) {
    /**选择了体重 */
    console.log(e.detail.value)
    this.setData({
      bodyweight_ind: e.detail.value
    })
  },
  sex: function (e) {
    /**选择了性别 */
    console.log(e.detail.value)
    this.setData({
      sex_ind: e.detail.value
    })
  },
  age: function (e) {
    /**选择了年龄 */
    console.log(e.detail.value)
    this.setData({
      age_ind: e.detail.value,
      istip_age: false //选择了年龄就关闭红色提示框
    })
  },
  education: function (e) {
    /**选择了学历 */
    console.log(e.detail.value)
    this.setData({
      education_ind: e.detail.value
    })
  },
  family: function (e) {
    /**选择了家庭 */
    console.log(e.detail.value)
    this.setData({
      family_ind: e.detail.value
    })
  },
  marriage: function (e) {
    /**选择了婚姻状态 */
    console.log(e.detail.value)
    this.setData({
      marriage_ind: e.detail.value
    })
  },
  houses: function (e) {
    /**选择了房屋状况 */
    console.log(e.detail.value)
    this.setData({
      houses_ind: e.detail.value
    })
  },

  switchChange: function (e) {
    /**用户选择了图片密码 */
    console.log(e)
    this.setData({
      isSwitch: e.detail.value
    })
  },
  dizhiChange: function (e) {
    /**选择了用户的地址 */
    this.setData({
      region: e.detail.value
    })

  },
  add: function () {
    /**用户选择照片 */
    var that = this;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res);
        that.setData({
          imagetemp: that.data.imagetemp.concat(res.tempFilePaths)
        })
      }
    })
  },
  imgshow: function (e) {
    //增加报告时用户点击图片显示全屏 
    wx.previewImage({
      current: this.data.imagetemp[e.currentTarget.dataset.index], // 当前显示图片的http链接  
      urls: this.data.imagetemp // 需要预览的图片http链接列表  
    })
  },
  delImg: function (e) {
    //删除图片
    var oldArr = this.data.imagetemp
    let id = e.currentTarget.dataset.id
    var newArr = []
    for (let i = 0; i < oldArr.length; i++) {
      if (i != id) {
        newArr.push(oldArr[i])
      }
    }
    this.setData({
      imagetemp: newArr
    })
  },
  uploadVideo: function () {
    //上传视频
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        //console.log(res.tempFilePath)

        wx.showLoading({
          title: '正在上传视频',
        })

        wx.cloud.uploadFile({
          cloudPath: `user/${time.formatTime(new Date)}/${Math.floor(Math.random() * 100000000)}.mp4`, // 上传至云端的路径
          filePath: res.tempFilePath, // 临时文件路径
          success: res => {
            wx.hideLoading()
            that.setData({
              videolist: that.data.videolist.concat(res.fileID)
            })
          }
        })

      }
    })
  },
  delvideo: function (e) {
    //删除视频
    var oldArr = this.data.videolist
    let id = e.currentTarget.dataset.id
    var newArr = []
    for (let i = 0; i < oldArr.length; i++) {
      if (i != id) {
        newArr.push(oldArr[i])
      }
    }
    //删除对应的视频文件
    wx.cloud.deleteFile({
      fileList: [oldArr[id]],
      success: res => {
        //删除成功
        console.log(res.fileList)
      },
      fail: console.error
    })

    this.setData({
      videolist: newArr
    })
  },
  switch2Checked:function(e){
    //用户点击了是否允许转发朋友圈
    this.setData({
      switch2Checked:e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})